#include "game.h"

Game::Game(QObject *parent)
	: QObject(parent), currentPlayer_(1), numPlayers_(2)
{
	boardSize_ = QSize(3,3);
	V.resize(boardSize_.height());
	for( int i=0; i<V.size(); i++ )
		V[i].resize(boardSize_.width());
}


void Game::checkStatus(Keyboard*k)
{
	// Update our array of plays
	for( int i=0; i<boardSize_.height(); i++ )
	{
		for( int j=0; j<boardSize_.width(); j++ )
		{
			V[i][j] = k->value(i,j);
		}
	}

	// Check rows
	for( int row = 0; row < boardSize_.height(); row++ )
	{
		int numMatches = 1;
		for( int col = 1; col < boardSize_.width(); col++ )
		{
			if( V[row][col] == V[row][col-1] && V[row][col]!=0 )
				numMatches++;
		}
		if( numMatches == boardSize_.width() )
		{
			lineMatch( ROW, row );
			return;
		}
	}

	// Check columns
	for( int col = 0; col < boardSize_.width(); col++ )
	{
		int numMatches = 1;
		for( int row = 1; row < boardSize_.height(); row++ )
		{
			if( V[row][col] == V[row-1][col] && V[row][col]!=0 )
				numMatches++;
		}
		if( numMatches == boardSize_.height() )
		{
			lineMatch( COL, col );
			return;
		}
	}

	// Check diagonals
	if( boardSize_.width() == boardSize_.height() )
	{
		// diagonal 0 (topleft to bottomright)
		int numMatches = 1;
		for( int col = 1; col < boardSize_.width(); col++ )
		{
			int row = col;
			if( V[row][col] == V[row-1][col-1] && V[row][col]!=0 )
				numMatches++;
		}
		if( numMatches == boardSize_.width() )
		{
			lineMatch( DIAG, 0 );
			return;
		}

		// diagonal 1 (topright to bottomleft)
		numMatches = 1;
		for( int col = 1; col < boardSize_.width(); col++ )
		{
			int row = boardSize_.height()-1-col;
			if( V[row][col] == V[row+1][col-1] && V[row][col]!=0 )
				numMatches++;
		}
		if( numMatches == boardSize_.width() )
		{
			lineMatch( DIAG, 1 );
			return;
		}
	}

	currentPlayer_++;
	if( currentPlayer_ > numPlayers_ ) currentPlayer_ -= numPlayers_;

}

void Game::lineMatch(int type, int num)
{
	int winnerPlayer = -1;
	switch( type )
	{
		case ROW:
			winnerPlayer = V[num][0];
		break;
		case COL:
			winnerPlayer = V[0][num];
		break;
		case DIAG:
			switch( num )
			{
				case 0:
					winnerPlayer = V[0][0];
				break;
				case 1:
					winnerPlayer = V[0].last();
				break;
			}
		break;
	}
	qDebug() << "Game over! ";
	qDebug() << "Player " << winnerPlayer << " has won!!";
}

